package com.xiangban.springTask;

import com.xiangban.dao.AccompanyMapper;
import com.xiangban.dao.RelationMapper;
import com.xiangban.model.Relation;
import com.xiangban.model.UserAccompany;
import com.xiangban.model.dto.UserAccompanyDto;
import com.xiangban.utils.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.List;



/**
 * 每月一号00:00:00重置（增加）患者免费次数
 *
 * @Author Mr. MaYaYun
 * @Data 2021/12/15 14:01
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class RelationFreeNumber {

    private static Logger LOGGER = LoggerFactory.getLogger(UserAccompanyGrade.class);

    @Autowired
    private RelationMapper relationMapper;
    @Autowired
    private CommonUtils commonUtils;


    //3.添加定时任务
    @Scheduled(cron = "0 0 0 1 * ?")
    //或首次延迟指定时间后执行直接指定时间间隔，例如：仅第一次程序开始是延迟10秒后 然后每间隔5秒开始执行程序一次
//    @Scheduled(initialDelay = 10000, fixedRate=5000)
    private void configureTasks() {
        LOGGER.info("执行静态定时任务时间开始: " + LocalDateTime.now());

        List<Relation> relationIdCard = relationMapper.getRelationIdCard();
        for (Relation relation : relationIdCard) {
            // 调用校验身份证的函数，若身份证完全正确，此处可以不需要

            int freeNumber = 0;//免费次数
            if (relation.getIdCard() != null && !"".equals(relation.getIdCard())
                    && (relation.getIdCard().length() == 15 || relation.getIdCard().length() == 18)){
                //获取年龄
                int age = commonUtils.getAgeByIdCard(relation.getIdCard());
                if (age < 70 ){
                    freeNumber = 1;
                }else if ( age >= 80){
                    freeNumber = 3;
                }else {
                    freeNumber = 2;
                }

                relation.setFreeNumber(freeNumber);
                relationMapper.updateUserFeeNumber(relation);

            }else {
                LOGGER.info("此用户身份证有误: " + relation.getIdCard());
            }
        }
        LOGGER.info("执行静态定时任务时间结束: " + LocalDateTime.now());
    }



}
